package com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.skytech.tax.customsdatawarehouse.common.util.SecurityUtil;
import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.dao.ManualDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.dao.ManualSimpleDao;
import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.entity.Manual;
import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.entity.ManualSimple;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lianhong
 * @since 2021/11/11
 */
@Service
public class ManualService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ManualService.class);

    @Value("${customsdatawarehouse.token}")
    private String token;

    @Resource
    private ManualDao manualDao;
    @Resource
    private ManualSimpleDao manualSimpleDao;

    public String save(String manual) {
        if (StringUtils.isEmpty(manual)) return StringUtils.EMPTY;
        String booksText = SecurityUtil.decrypt3DES(token, manual);
        try {
            Manual m = JSON.parseObject(booksText, Manual.class);
            if (m == null) return StringUtils.EMPTY;

            m.addFields();
            ManualSimple simple = m.buildManualSimple();
            if (simple == null) return StringUtils.EMPTY;

            this.remove(m.getSeqNo());

            manualDao.save(m);
            manualSimpleDao.save(simple);
            return SecurityUtil.encrypt3DES(token, m.getManual());
        } catch (Exception e) {
            LOGGER.error("保存加工贸易手册错误", e);
            return StringUtils.EMPTY;
        }
    }

    public String details(String seqNo) {
        Manual manual = manualDao.findBySeqNo(seqNo);
        if (manual == null) return StringUtils.EMPTY;
        return SecurityUtil.encrypt3DES(token, manual.getManual());
    }

    public void remove(String seqNo) {
        manualDao.delete(seqNo);
        manualSimpleDao.delete(seqNo);
    }

    public boolean exists(String seqNo) {
        return manualSimpleDao.exists(seqNo);
    }

    public String existsManuals(List<String> seqNos) {
        if (CollectionUtils.isEmpty(seqNos)) return StringUtils.EMPTY;
        List<List<String>> parts = Lists.partition(seqNos, 500);
        List<String> result = new ArrayList<>();
        parts.forEach(item -> result.addAll(manualSimpleDao.exists(item)));
        return StringUtils.join(result, ",");
    }
}
